package com.hewep.demo.device;

import java.io.IOException;
import java.net.InetSocketAddress;

import com.hewep.demo.device.mina.core.Constants;
import com.hewep.demo.device.mina.core.Routes;
import com.hewep.demo.device.mina.core.codec.DeviceCodecFactory;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public abstract class Server {
	
	private ServerConfig config = new ServerConfig();
		
	private String ipAddr = "192.168.0.250";
	private int port = 5001;
	private NioSocketConnector connector;	
	private ServerIoHandler serverHandler;
	
	
	public String getIpAddr() {
		return ipAddr;
	}

	public void setIpAddr(String ipAddr) {
		this.ipAddr = ipAddr;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
		
	public ServerConfig getConfig() {
		return config;
	}
	
	public abstract void configConstant(Constants me);
	
	public abstract void configRoute(Routes me);
	
	public boolean start() throws IOException{
		configConstant(config.getConstants());
		configRoute(config.getRoutes());
		
		this.serverHandler = new ServerIoHandler(config);		
		
		connector  =  new NioSocketConnector();
		connector.setConnectTimeoutMillis(15000);
		connector.getFilterChain().addFirst("logging", new org.apache.mina.filter.logging.LoggingFilter());
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new DeviceCodecFactory()));
		connector.setHandler(serverHandler);
        connector.getSessionConfig().setUseReadOperation(true);
        
        ConnectFuture connect = connector.connect(new InetSocketAddress(this.ipAddr, this.port));
        boolean connected = connect.isConnected();
        
        if(!connected){
        	connect.cancel();
        }
        return connect.isConnected();
	}
	
	public void stop(){
		connector.dispose();
	}
   
    public boolean isStopped(){
    	return false;
    }
}
